/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package comandaXM.utils.format;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;

import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class FormatJSplitPaneXML_DOM {

        private Document dom;
        
        public FormatJSplitPaneXML_DOM() {
                dom = null;
        }
               
        private void addCol(int colWidth) {
                //Seleccionamen l'arrel
                Element root = dom.getDocumentElement();                
                // Creem un nou element
                Element col = dom.createElement("Col");
                col.setAttribute("Width", String.valueOf(colWidth));                                
                // s'inserta l'element a l'arrel
                root.appendChild(col);
        }
        private void addResize(int colWidth) {                
                Element root = dom.getDocumentElement();               
                Element col = dom.createElement("Resize");
                col.setAttribute("Heigh", String.valueOf(colWidth));                                
                root.appendChild(col);
        }
        private void addForm(int formWidth, int formHeight) {                
                Element root = dom.getDocumentElement();               
                Element col = dom.createElement("Form");
                col.setAttribute("Heigh", String.valueOf(formHeight));
                col.setAttribute("Width", String.valueOf(formWidth));
                root.appendChild(col);
        }
        
        /*
         * Escribe en el fichero la representacion del árbol XML
         */
        private void write(StringWriter sw, String path) throws IOException {                
            // creamos fichero para escribir en modo texto
            PrintWriter writer = new PrintWriter(new FileWriter(path));
            // escribimos todo el arbol en XML
            writer.println(sw.toString());
            // cerramos el fichero
            writer.close();

        }

        /*
         * Transforma el árbol, agregando la cabecera y añadiendo sangrados
         */
        private void toFile(String ruta) throws TransformerConfigurationException, TransformerException, IOException {
//                try {
                        // volcamos el XML al fichero
                        TransformerFactory transFact = TransformerFactory.newInstance();                
                        // añadimos sangrado
                        transFact.setAttribute("indent-number", new Integer(3));
                        Transformer trans = transFact.newTransformer();
                        // incluimos la cabecera XML y el sangrado
                        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                        trans.setOutputProperty(OutputKeys.INDENT, "yes");                
                        // hacemos la transformacion
                        StringWriter sw = new StringWriter();
                        StreamResult sr = new StreamResult(sw);
                        DOMSource domSource = new DOMSource(dom);
                        trans.transform(domSource, sr);                        
                        // escribimos en el fichero
                        write(sw, ruta);
//                } catch(Exception ex) {
//                        ex.printStackTrace();
//                }
        }
        
        /*
         * Creamos un fichero XML a partir de una lista de pedidos
         */
        public void FormatJSplitPaneToXML(FormatJSplitPane format, String ruta) throws TransformerException, TransformerConfigurationException, IOException, ParserConfigurationException {
                // creamos un nuevo Document donde vamos a guardar toda la estructura
               
                dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element root = dom.createElement("format");
                dom.appendChild(root);

                List list= format.getCols(); 
                for(int i = 0; i < list.size(); i++) addCol((int) list.get(i));
                addResize ((int)format.getResizeWeight());
                addForm((int) format.getFormWidth(),(int) format.getFormHeight());
                // volcamos por pantalla
                toFile(ruta);
        }
        
        
        
        
        private int readWidth(Node nodeCol) {
                Element elementoPedido = (Element)nodeCol;                
                int col = Integer.valueOf(elementoPedido.getAttribute("Width"));                
                return col;
        }
        private int readHeight(Node nodeCol) {
                Element element = (Element)nodeCol;                
                int heigh = Integer.valueOf(element.getAttribute("Heigh"));                
                return heigh;
        }
       
        /*
         * Creamos una lista de pedidos procesando un fichero XML
         */
        public FormatJSplitPane XMLtoFormatJSplitPane(String ruta) throws ParserConfigurationException, IOException, SAXException {
                FormatJSplitPane format=null; 
                ArrayList<Integer> cols = new ArrayList<Integer>();                
              
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        dom = db.parse(new File(ruta));
                        dom.getDocumentElement().normalize();
                        format= new FormatJSplitPane ();
                        // seleccionamos todos los pedidos y vamos leyendo
                        NodeList llistaCols = dom.getDocumentElement().getElementsByTagName("Col");
                        for(int i = 0; i < llistaCols.getLength(); i++) {
                                cols.add(readWidth(llistaCols.item(i)));
                        }
                        format.setCols(cols);
                        
                        NodeList resize= dom.getDocumentElement().getElementsByTagName("Resize");                                                
                        if(resize.getLength()>0) format.setResizeWeight(readHeight(resize.item(0)));
                        
                        NodeList form= dom.getDocumentElement().getElementsByTagName("Form");                                                                        
                        if(form.getLength()>0) {
                            format.setFormHeight(readHeight(form.item(0)));
                            format.setFormWidth(readWidth(form.item(0)));
                        }
                        
                
                return format;
        }
}